<template>
  <div v-if="isVisible" class="modal-overlay" ref="modalRef">
    <!-- 头部 -->
    <div class="bg-blue-600 text-white px-6 py-4 flex items-center justify-between">
      <h2 class="text-xl font-semibold">选择助手</h2>
      <button @click="closeAssistant" class="text-white hover:text-gray-200">
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
        </svg>
      </button>
    </div>

    <!-- 左右布局 -->
    <div class="flex h-[calc(100vh-80px)]">
      <!-- 左侧：规则配置 -->
      <div class="w-96 bg-white border-r border-gray-200 p-4 overflow-y-auto">
        <div class="space-y-6">
          <!-- 选择规则 -->
          <SelectionRules />
          
          <!-- 文本模式选择 -->
          <TextModeSelection />
          
          <!-- 目录位置选择 -->
          <LocationSelection />
          
          <!-- 操作按钮 -->
          <SelectionActions 
            :selected-count="selectedCount"
            :duplicate-count="actualDuplicateFiles"
            :saved-space="actualSavedSpace"
          />
        </div>
      </div>

      <!-- 右侧：结果预览 -->
      <div class="flex-1 bg-gray-50 p-4 overflow-y-auto">
        <h3 class="text-lg font-semibold mb-4">选择结果预览</h3>
        
        <div class="space-y-4">
          <div v-for="(group, groupIndex) in duplicateGroupsList" :key="groupIndex" class="bg-white rounded-lg p-4 border shadow-sm">
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center space-x-2">
                <span class="font-semibold">组 {{ groupIndex + 1 }}</span>
                <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded">{{ group.files.length }} 个文件</span>
                <span class="px-2 py-1 bg-green-100 text-green-800 text-xs rounded">{{ formatFileSize(group.size) }}</span>
              </div>
              <div class="flex space-x-2">
                <button @click="selectAllInGroup(groupIndex)" class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white text-sm rounded-lg transition-colors">
                  全选
                </button>
                <button @click="deselectAllInGroup(groupIndex)" class="px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white text-sm rounded-lg transition-colors">
                  取消全选
                </button>
              </div>
            </div>
            
            <div class="space-y-2">
              <div v-for="(file, fileIndex) in group.files" :key="fileIndex" class="flex items-center space-x-3 p-2 bg-gray-50 rounded border hover:bg-gray-100">
                <input 
                  type="checkbox" 
                  :id="`file-${groupIndex}-${fileIndex}`"
                  v-model="file.selected"
                  class="w-4 h-4 text-blue-600 border-gray-300 rounded"
                >
                <label :for="`file-${groupIndex}-${fileIndex}`" class="flex-1 cursor-pointer">
                  <div class="flex items-center space-x-3">
                    <div class="w-6 h-6 bg-gray-100 rounded flex items-center justify-center">
                      <svg class="w-3 h-3 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                      </svg>
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="font-medium text-gray-900 truncate text-sm">{{ file.name }}</div>
                      <div class="text-xs text-gray-500 truncate">{{ file.path }}</div>
                    </div>
                    <div class="text-right">
                      <div class="text-sm font-medium text-gray-900">{{ formatFileSize(file.size) }}</div>
                      <div class="text-xs text-gray-500">{{ formatDate(file.modified) }}</div>
                    </div>
                  </div>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import SelectionRules from './SelectionRules.vue'
import TextModeSelection from './TextModeSelection.vue'
import LocationSelection from './LocationSelection.vue'
import SelectionActions from './SelectionActions.vue'

interface FileInfo {
  name: string
  path: string
  size: number
  modified: Date
  selected: boolean
}

interface DuplicateGroup {
  files: FileInfo[]
  size: number
}

interface Props {
  isVisible: boolean
  duplicateGroupsList: DuplicateGroup[]
}

interface Emits {
  (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算属性
const selectedCount = computed(() => {
  return props.duplicateGroupsList.reduce((total, group) => {
    return total + group.files.filter(file => file.selected).length
  }, 0)
})

const actualSavedSpace = computed(() => {
  let totalSaved = 0
  props.duplicateGroupsList.forEach(group => {
    const selectedFiles = group.files.filter(file => file.selected)
    if (selectedFiles.length > 1) {
      const filesToDelete = selectedFiles.slice(1)
      filesToDelete.forEach(file => {
        totalSaved += file.size
      })
    }
  })
  return formatFileSize(totalSaved)
})

const actualDuplicateFiles = computed(() => {
  return props.duplicateGroupsList.reduce((total, group) => {
    const selectedFiles = group.files.filter(file => file.selected)
    if (selectedFiles.length > 1) {
      total += selectedFiles.length - 1
    }
    return total
  }, 0)
})

// 方法
const closeAssistant = () => {
  emit('close')
}

const selectAllInGroup = (groupIndex: number) => {
  props.duplicateGroupsList[groupIndex].files.forEach(file => {
    file.selected = true
  })
}

const deselectAllInGroup = (groupIndex: number) => {
  props.duplicateGroupsList[groupIndex].files.forEach(file => {
    file.selected = false
  })
}

// 工具函数
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (date: Date): string => {
  return date.toLocaleDateString('zh-CN')
}

// 弹窗定位管理
const modalRef = ref<HTMLElement | null>(null)

// 动态定位弹窗
const positionModal = () => {
  if (modalRef.value) {
    const modal = modalRef.value
    // 强制设置弹窗位置
    modal.style.position = 'fixed'
    modal.style.top = '0px'
    modal.style.left = '0px'
    modal.style.width = '100vw'
    modal.style.height = '100vh'
    modal.style.zIndex = '9999'
    
    // 确保弹窗内容居中
    const content = modal.querySelector('.modal-content') as HTMLElement
    if (content) {
      content.style.position = 'absolute'
      content.style.top = '50%'
      content.style.left = '50%'
      content.style.transform = 'translate(-50%, -50%)'
    }
  }
}

// 监听窗口变化
const handleResize = () => {
  positionModal()
}

// 监听弹窗显示状态
watch(() => props.isVisible, (newValue) => {
  if (newValue) {
    nextTick(() => {
      positionModal()
    })
  }
})

// 组件挂载后设置弹窗定位
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载后清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
